// ES5 语法
var React = require('react')
var Reactnative = require('react-native');
var Icon = require('react-native-vector-icons/Ionicons');
var config = require('../common/config');
var request = require('../common/request');
//详情页
var Detail = require('./detail');


var Component = React.Component;
var AppRegistry = Reactnative.AppRegistry;
var StyleSheet = Reactnative.StyleSheet
var Text = Reactnative.Text
var View = Reactnative.View
var ListView = Reactnative.ListView
var TouchableHighlight =Reactnative.TouchableHighlight
var Image = Reactnative.Image
var AlertIOS = Reactnative.AlertIOS
var Dimensions = Reactnative.Dimensions
var ActivityIndicator = Reactnative.ActivityIndicator
var RefreshControl = Reactnative.RefreshControl
var width = Dimensions.get('window').width

//页码或缓存列表所有的数据
var cachedResuults = {
  nextPage:1,
  items:[],
  total:0
}

var Item =  React.createClass({
  getInitialState:function(){
    var row = this.props.row;

    return {
      up:row.voted,
      row : row
    }
  },
 
  _up() {
    var up = !this.state.up,
        row = this.state.row,
        that = this,
        url = config.api.base + config.api.up;
        //console.log(url,up)
    var body = {
          id:row._id,
          up:up ? 'yes' : 'no',
          accessToken:'abcee'
        }; 
    //return    
    request.post(url,body)
      .then(function(data){
        console.log(data.suceess)
        if(data.suceess && data) {
          that.setState({
            up:up
          })
        }else{
          AlertIOS.alert('点赞失败，请稍后再试')
        }
      })
      .catch(function(err){
        console.log(err)
      })    
  },
  render (){
    var row = this.state.row;
    return (
           <TouchableHighlight onPress={this.props.onSelect}>
              <View style={styles.item}>
                  <Text style={styles.title}>{row.title}</Text>
                       <Image
                          style={styles.thumb}
                          source={{uri: row.thumb}}
                        >
                        <Icon name="ios-play" size={28} style={styles.play} />
                        </Image>
                        <View style={styles.itemFooter} >
                              <View style={styles.handleBox} >
                                  <Icon name={ this.state.up ? 'ios-heart' : 'ios-heart-outline' } 
                                  size={28} 
                                  style={[styles.up, this.state.up ? null : styles.down]} 
                                  onPress={this._up}
                                  />
                                  <Text style={styles.handleText} onPress={this._up} >喜欢</Text>
                              </View>
                              <View style={styles.handleBox} >
                                  <Icon name="ios-chatboxes-outline" size={28} style={styles.commentIcon} />
                                  <Text style={styles.handleText} >评论</Text>
                              </View>
                         </View>        
                </View>
            </TouchableHighlight>
      )
  }
})

//第一个组件组件
var List =  React.createClass({
  getInitialState:function(){
    var ds = new ListView.DataSource({
        rowHasChanged: (r1, r2) => r1 !== r2
    });
    return {
        isLoadingTail:false,
        isRefreshing:false,
        dataSource:ds.cloneWithRows([
            // {
            //     "_id":"650000201207058288","thumb":"https://dummyimage.com/1280x720/c8fa58)","title":"测试内容zor3","video":"http://v2.mukewang.com/92c5d142-48ef-40f8-ad7e-8bf4f75a3f39/L.mp4?auth_key=1478436971-0-0-a41e95ef6d3892aa6d3f79699efcad09"
            // },
            // {
            //     "_id":"330000198003261584","thumb":"https://dummyimage.com/1280x720/fd73b4)","title":"测试内容zor3","video":"http://v2.mukewang.com/92c5d142-48ef-40f8-ad7e-8bf4f75a3f39/L.mp4?auth_key=1478436971-0-0-a41e95ef6d3892aa6d3f79699efcad09"
            // },
            // {
            //     "_id":"430000200007077147","thumb":"https://dummyimage.com/1280x720/68e2ee)","title":"测试内容zor3","video":"http://v2.mukewang.com/92c5d142-48ef-40f8-ad7e-8bf4f75a3f39/L.mp4?auth_key=1478436971-0-0-a41e95ef6d3892aa6d3f79699efcad09"
            // },
            // {
            //     "_id":"51000020050625198X","thumb":"https://dummyimage.com/1280x720/99db88)","title":"测试内容zor3","video":"http://v2.mukewang.com/92c5d142-48ef-40f8-ad7e-8bf4f75a3f39/L.mp4?auth_key=1478436971-0-0-a41e95ef6d3892aa6d3f79699efcad09"
            // },
            // {
            //     "_id":"610000201207251398","thumb":"https://dummyimage.com/1280x720/dbaaf8)","title":"测试内容zor3","video":"http://v2.mukewang.com/92c5d142-48ef-40f8-ad7e-8bf4f75a3f39/L.mp4?auth_key=1478436971-0-0-a41e95ef6d3892aa6d3f79699efcad09"
            // },
            // {
            //     "_id":"320000199302255101","thumb":"https://dummyimage.com/1280x720/c38a2a)","title":"测试内容zor3","video":"http://v2.mukewang.com/92c5d142-48ef-40f8-ad7e-8bf4f75a3f39/L.mp4?auth_key=1478436971-0-0-a41e95ef6d3892aa6d3f79699efcad09"
            // },
            // {
            //     "_id":"15000019720321272X","thumb":"https://dummyimage.com/1280x720/a76e1b)","title":"测试内容zor3","video":"http://v2.mukewang.com/92c5d142-48ef-40f8-ad7e-8bf4f75a3f39/L.mp4?auth_key=1478436971-0-0-a41e95ef6d3892aa6d3f79699efcad09"
            // }
        ])
    }
  },  
  _renderRow:function(row){
    return <Item key={row._id} 
            onSelect={()=> this._loadPage(row)}
             row={row} />
  }, 
  componentDidMount:function(){
    this._fetchData(1)
  },
  _fetchData:function(page){
    var _selft = this;
    if(page !==0){
       this.setState({
         isLoadingTail:true  
       })
    }else{
      this.setState({
        isRefreshing:true
      }) 
    }
   
     request.get(config.api.base + config.api.creations,{
        accrssToken:'longlong',
        page:page
     })
      .then((data) => {
        if(data.succes){
            var itmes = cachedResuults.items.slice();
            if(page !==0){
               itmes = itmes.concat(data.data)
               cachedResuults.nextPage += 1;
             }else{
               itmes = data.data.concat(itmes)
             }
         
            cachedResuults.items = itmes;
            cachedResuults.total = data.total;
            if(page !==0){
              this.setState({
                isLoadingTail:false,  
                dataSource:_selft.state.dataSource.cloneWithRows(
                  cachedResuults.items)
              })
            }else{
              this.setState({
                isRefreshing:false,  
                dataSource:_selft.state.dataSource.cloneWithRows(
                  cachedResuults.items)
              })
            }
        }
      })
      .catch((error) => {
        if(page !==0){
          this.setState({
            isLoadingTail:false
          })
        }else{
          this.setState({
            isRefreshing:false
          })
        }
        console.warn(error);
      });
  
 },
  _hasMore:function(){
    return cachedResuults.items.length !== cachedResuults.total
  },
  _fetchMoreData:function(){
    //如果是没有更多数据了或者已经在加载中了
    if(!this._hasMore() || this.isLoadingTail){
      return
    }
    let page = cachedResuults.nextPage;
    this._fetchData(page);
  },
  _onRefresh:function(){
   if(!this._hasMore ||this.state.isRefreshing){
     return
   }
   this._fetchData(0);
  },
  _rendFooter:function(){
    if(!this._hasMore() && cachedResuults.total !== 0){
      return (
        <View style={styles.loadingMore}>
          <Text style={styles.loadingText}>没有更多了</Text>
        </View>  
      )
    }
    if(!this.state.isLoadingTail){
      return <View style={styles.loadingMore}></View>
    }  
    return <ActivityIndicator 
      style={styles.loadingMore} 
    />
  }, 
  _loadPage(row) {
    this.props.navigator.push({
      name:'detail',
      component:Detail,
      params:{
        data:row
      }
    })
  }, 
  render:function(){
    return (
      <View style={styles.container}>
          <View style={styles.header}>
            <Text style={styles.headerTitle}>列表页面</Text>
          </View>
          <ListView
          dataSource={this.state.dataSource}
          onEndReached ={this._fetchMoreData}
          refreshControl={
            <RefreshControl
              refreshing={this.state.isRefreshing}
              onRefresh={this._onRefresh}
              tintColor="#ff6600"
              title="拼命加载中..."
            />
          }
          onEndReachedThreshold ={20}
          renderFooter ={this._rendFooter}  
          renderRow={this._renderRow}
          enableEmptySections={true} 
          showsVerticalScrollIndicator={false}
          automaticallyAdjustContentInsets={false} 
          />
      </View>
    )
  }         
}) 

 var styles = StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: '#f5fcff',
    },
    header:{
        paddingTop:25,
        paddingBottom:12,
        backgroundColor:'#ee735c'    
    },
    headerTitle:{
        color:'#fff',
        fontSize:16,
        textAlign:'center',
        fontWeight:'600'
    },
    item:{
        width:width,
        marginBottom:10,
        backgroundColor:'#fff'
    },
    thumb:{
         width:width,
         height:width * 0.5,
         resizeMode:'cover'
    },
    title:{
        padding:10,
        fontSize:18
    },
    itemFooter:{
        flexDirection:'row',
        justifyContent:'space-between',
        backgroundColor:'#eee'
    },
    handleBox:{
        padding:10,
        flexDirection:'row',
        width:width/2-0.5,
        justifyContent:'center',
        backgroundColor:'#fff'
    },
    play:{
        position:'absolute',
        bottom:14,
        right:14,
        width:46,
        height:46,
        paddingTop:9,
        paddingLeft:18,
        backgroundColor:'transparent',
        borderColor:'#fff',
        borderWidth:1,
        borderRadius:23,
        color:'#ed7b66'
    },
    handleText:{
        paddingLeft:12,
        fontSize:18,
        color:'#333'
    },
    up:{
       fontSize:22,
       color:'#ed7b66' 
    },
    down:{
       fontSize:22,
       color:'#333' 
    },
    commentIcon: {
       fontSize:22,
       color:'#333'
    },
    loadingMore:{
      marginVertical:20
    },
    loadingText:{
      color:'#777',
      textAlign:'center'
    }
  });

 module.exports =  List